package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

/*聊天室服务器端*/
public class Server {
    private ServerSocket severSocket;
    //private PrintWriter[] allOut = {};
    private Collection<PrintWriter>allOut=new ArrayList<>();

    public Server() {
        try {
            System.out.println("正在启动服务端");
            severSocket = new ServerSocket(8088);
            System.out.println("服务端启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void start() {
        try {
            while (true) {

                System.out.println("等待客户端连接");
                Socket socket = severSocket.accept();
                System.out.println("客户端连接了！");

                Runnable handler = new ClientHandler(socket);
                Thread t = new Thread(handler);
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static void main(String[] args) {
        Server sever = new Server();
        sever.start();
    }

    /*该线程是负责与指定客户端进行交互*/
    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;//记录远端计算机地址信息

        public ClientHandler(Socket socket) {
            this.socket = socket;
            //通过socket获取远端计算机地址信息
            host = socket.getInetAddress().getHostAddress();
        }

        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                /*获取输出流并进行流连接给客户端发信息*/
                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw, true);
                synchronized (allOut) {
                   /* //将数组扩容
                    allOut = Arrays.copyOf(allOut, allOut.length + 1);
                    //将pw放入数组
                    allOut[allOut.length - 1] = pw;*/
                    allOut.add(pw);
                }
                sendMessage(host + "上线了，当前在线人数" + allOut.size());

                String line;
                while ((line = br.readLine()) != null) {
                    sendMessage(host + "说" + line);
                }
            } catch (IOException e) {
                //当客户端强行关闭 服务端这里readline会抛出异常，这里就可以catch异常
            } finally {
                synchronized (allOut) {
                    //将当前pw从allout数组中删除
                   /* for (int i = 0; i < allOut.length; i++) {
                        if (allOut[i] == pw) {
                            allOut[i] = allOut[allOut.length - 1];
                            allOut = Arrays.copyOf(allOut, allOut.length - 1);
                            break;
                        }
                    }*/
                  allOut.remove(pw);
                }
                sendMessage(host + "下线了，当前在线人数" + allOut.size());

                try {
                    socket.close();//关闭socket释放资源
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        //广播消息给每一个客户端
        private void sendMessage(String line) {
            System.out.println(line);
            synchronized (allOut) {
                //将消息转发给客户端
                /*for (int i = 0; i < allOut.length; i++) {
                    allOut[i].println(line);//将消息发送给客户端
                }*/
                for (PrintWriter pw :allOut){
                    pw.println(line);
                }
            }
        }

    }
}
